<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Customer as CustomerModel;
use app\common\model\Follow as FollowModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\service\UserPermissionService;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

/**
 * 首页接口
 */
class Follow extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    public function getStatistics()
    {
        $follow = new FollowModel();
        $userId = $this->auth->id;

        //数据权限
        $userPermissionService = new UserPermissionService();
        $staffids=$userPermissionService->getUsersByPermission($this->auth->id);
        $baseWhere = [];
        $baseWhere['staff_id']=['in',$staffids];
        $baseWhere['is_delete']=0;

        // 1. 全部 - 使用数据权限过滤
        $totalAll = $follow->where($baseWhere)->count();

        // 2. 我创建的 - 使用数据权限 + 当前用户
        $totalMine = $follow->where($baseWhere)->where('staff_id', $userId)->count();

        // 3. 下属创建的 - 使用数据权限 + 下属用户
        $subStaffids = Db::name('user')->where('leader_id', $userId)->column('id');
        if ($subStaffids) {
            $totalSub = $follow->where($baseWhere)->where('staff_id', 'in', $subStaffids)->count();
        } else {
            $totalSub = 0;
        }

        // 4. 今日待跟进（今日没有跟进的客户数）- 这个统计比较复杂，暂时注释掉
        // $todayStart = strtotime(date('Y-m-d 00:00:00'));
        // $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        // $followedCustomerIds = $follow->where($baseWhere)->where('followtime', 'between', [$todayStart, $todayEnd])->distinct(true)->column('customer_id');
        // $customerModel = new \app\common\model\Customer();
        // $totalTodayWait = $customerModel->whereNotIn('id', $followedCustomerIds ?: [0])->count();

        // 5. 今日已跟进（今日有跟进的客户数）- 使用数据权限 + 今日时间范围
        $todayStart = strtotime(date('Y-m-d 00:00:00'));
        $todayEnd = strtotime(date('Y-m-d 23:59:59'));
        $totalTodayFollow = $follow->where($baseWhere)->where('followtime', 'between', [$todayStart, $todayEnd])->count();

        $data = [
            ['type' => 1, 'title' => '全部', 'value' => $totalAll],
            ['type' => 2, 'title' => '我创建的', 'value' => $totalMine],
            ['type' => 3, 'title' => '下属创建的', 'value' => $totalSub],
            // ['type' => 4, 'title' => '今日待跟进', 'value' => $totalTodayWait], // 暂时注释掉
            ['type' => 5, 'title' => '今日已跟进', 'value' => $totalTodayFollow],
        ];

        $this->success('success', $data);
    }
 


    public function getList()
    {
        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);
        $params = $this->request->post();
        // 新增 type 参数
        $type = $this->request->post('type', '');
        $action = $this->request->post('action', 'list'); // 新增：action参数，list或export
        
        // 使用统一的buildWhere方法构建查询条件
        $where = $this->buildWhere($params, $type);
        
        // 如果是导出操作
        if ($action === 'export') {
            return $this->handleExport($where, $params);
        }
        if ($action === 'delete') {
            return $this->handleDelete($where, $params);
        }
        
        // 构建查询条件
        $follow = new \app\common\model\Follow();
        $total = $follow
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->field('a.*, u.name as username')
            ->where($where)->count();
        $list = $follow
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->field('a.*, u.name as username,c.customerName')
            ->order('a.id', 'desc')
            ->where($where)
            ->page($page, $pageSize)
            ->select();

        // 格式化返回数据，附加 customerName 和 username
        $data = [];
        foreach ($list as $item) {
            $row = $item->toArray();
            $data[] = $row;
        }
        $this->success('请求成功', ['list' => $data, 'total' => $total]);
    }

    private function handleDelete($where, $params)
    {
        // 优先使用前端传入的 ids；若未提供，则根据 where 条件查询出匹配的记录ID
        $idsParam = $this->request->post('ids', []);
    

        // 使用与列表相同的关联查询获取 a.id 列表
        $ids = Db::name('follow a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->where($where)
            ->column('a.id');

        if (empty($ids)) {
            $this->error('没有找到需要删除的记录');
        }

            // 按ID更新，避免别名引起的歧义
        $result = Db::name('follow')
                ->where('id', 'in', $ids)
                ->update([
                    'is_delete' => 1,
                    'deletetime' => time(),
                ]);

        
            $deletedCount = $result ?: 0;
            $this->success("删除成功，共删除 {$deletedCount} 条记录");
       
    }
    public function getSelectFollow()
    {
        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);
        $customerId = $this->request->post('customerId', 'customerId');

        $where=[];
        $where['a.customer_id']=$customerId;
        $where['a.is_delete']=0;

        $follow = new \app\common\model\Follow();
        $total = $follow
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->field('a.*, u.name as username')
            ->where($where)->count();
        $list = $follow
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->field('a.*, u.name as username,c.customerName')
            ->order('a.id', 'desc')
            ->where($where)
            ->page($page, $pageSize)
            ->select();

        // 格式化返回数据，附加 customerName 和 username
        $data = [];
        foreach ($list as $item) {
            $row = $item->toArray();
            $data[] = $row;
        }
        $this->success('请求成功', ['list' => $data, 'total' => $total]);
    }


    public function createFollow(){
        $data = $this->request->post();

        // 验证必填字段
        if (empty($data['customerId']) || empty($data['followType']) ) {
            $this->error('缺少必要参数');
        }

        $followTime= $this->request->post('followTime',date('Y-m-d h:i:s'));
        $timestamp = strtotime($followTime);
        $followTime=date('Y-m-d H:i:s', $timestamp);

        $communicationStatus=$data['communicationStatus'];
        $communicationStatus=$communicationStatus?implode(',', $communicationStatus):'';
        try {

            // 处理图片数组
            if (isset($data['images']) && is_array($data['images'])) {

                $certificate=$data['images'];
                foreach($certificate as $key=>$value){
                    $certificate[$key]=removeDomainFromImageUrl($value);
                }
                $data['images'] = json_encode($certificate, JSON_UNESCAPED_UNICODE);
            }

            $createtime=time();
            $followModel = new \app\common\model\Follow();
            // 创建跟进记录
            $followModel::create([
                'customer_id' => $data['customerId'],
                'follow_type' => $data['followType'],
                'followtime' => $followTime,
                'communication_status' => $communicationStatus,
                'remark' => $data['remark'] ?? '',
                'images' => $data['images'] ?? '[]',
                'createtime' => $createtime,
                'updatetime' => time(),
                'user_id'=>$this->auth->id,
                'staff_id'=>$this->auth->id
            ]);
            // 更新客户表的沟通状态
            $customer = CustomerModel::where('id', $data['customerId'])->find();
            if ($customer) {
                $customer->communicationStatus = $communicationStatus;
                $customer->lastfollowcon = isset($data['remark'])?$data['remark']:null;
                $customer->lastfollowtime = $createtime;
                $customer->save();
            }
            $this->success('创建成功');

        } catch (Exception $e) {
            $this->error('创建失败');
        }
    }

    public function updateFollow()
    {
        $data = $this->request->post();

        if (empty($data['id'])) {
            $this->error('缺少跟进ID');
        }

        $follow = \app\common\model\Follow::get($data['id']);
        if (!$follow) {
            $this->error('跟进记录不存在');
        }

        // 处理沟通状态数组
        if (isset($data['communicationStatus']) && is_array($data['communicationStatus'])) {
            $communicationStatus=implode(',', $data['communicationStatus']);
        }else{
            $communicationStatus='';
        }

        // 处理图片数组
        if (isset($data['images']) && is_array($data['images'])) {

            $certificate=$data['images'];

            foreach($certificate as $key=>$value){
                $certificate[$key]=removeDomainFromImageUrl($value);
            }
            $data['images'] = json_encode($certificate, JSON_UNESCAPED_UNICODE);
        }

        $updateData = [
            'follow_type'          => $data['followType'] ?? $follow->follow_type,
            'followtime'          => isset($data['followTime']) ? date('Y-m-d H:i:s', strtotime($data['followTime'])) : $follow->followtime,
            'communication_status' => $communicationStatus ?? $follow->communication_status,
            'remark'               => $data['remark'] ?? $follow->remark,
            'images'               => $data['images'] ?? $follow->images,
            'updatetime'           => time(),
        ];

        $res = $follow->save($updateData);

        if ($res !== false) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }

    public function getFollowDetail()
    {
        $id = $this->request->post('id');
        if (!$id) {
            $this->error('缺少参数');
        }

        $follow = Db::name('follow')
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->join('customer c', 'a.customer_id = c.id', 'left')
            ->field('a.*, u.name as username, c.customerName')
            ->where('a.id', $id)
            ->find();

        if (!$follow) {
            $this->error('跟进记录不存在');
        }

        $data = $follow;
        
        $data['customerId'] = $follow['customer_id'];
        $data['customerName'] = $follow['customerName'] ?? '';
        $data['username'] = $follow['username'] ?? '';

        // 为图片URL添加域名前缀
        if (!empty($data['images'])) {
            $request = Request::instance();
            $domain = $request->domain();

            if (!empty($data['images'])) {
                $images= json_decode($data['images'], true);
                foreach ($images as $key=>$value){
                    $images[$key]=$domain.$value;
                }
                $data['images']=$images;
            }
            
        }

        $communication_status=$data['communication_status'];
        $data['communication_status'] = $communication_status?explode(',',$communication_status):[];
        $data['communicationStatus']=$communication_status;

        if (isset($data['images']) && is_string($data['images'])) {
            $data['images'] = json_decode($data['images'], true);
        }

        $this->success('获取成功', $data);
    }

    public function deleteFollow(){
        $ids = $this->request->post('ids', '');
        $ids=explode(',',$ids);
        $follow = new \app\common\model\Follow();
        $follow->whereIn('id',$ids)->update(['is_delete'=>1,'deletetime'=>time()]);
        $this->success();
    }
    public function getCommentList()
    {
        $followId = $this->request->post('followId');
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 10);

        if (empty($followId)) {
            $this->error('缺少跟进ID');
        }

        // 分别构建 count 查询和 select 查询，避免相互影响
        $countQuery = Db::name('follow_comment')
            ->alias('a')
            ->where('a.follow_id', $followId);
        
        $total = $countQuery->count();

        $listQuery = Db::name('follow_comment')
            ->alias('a')
            ->join('user u', 'a.user_id = u.id', 'left')
            ->field('a.*, u.name as username')
            ->where('a.follow_id', $followId)
            ->order('a.id desc');

        $list = $listQuery->page($page, $pageSize)->select();

        $data = [];
        foreach ($list as $item) {
            $row = $item;
            $row['user'] = $item['username'] ?? '';
            $row['time'] = date('Y-m-d H:i:s', $item['createtime']);
            $data[] = $row;
        }

        $this->success('获取成功', ['list' => $data, 'total' => $total]);
    }

    public function addComment()
    {
        $data = $this->request->post();

        // 校验参数
        if (empty($data['follow_id']) || empty($data['content'])) {
            $this->error('缺少必要参数');
        }

        // 获取当前用户ID（如果有登录验证）
        $userId = $this->auth ? $this->auth->id : 0;

        $comment = new \app\common\model\FollowComment();
        $comment->follow_id = $data['follow_id'];
        $comment->user_id = $userId;
        $comment->content = $data['content'];
        $comment->createtime = time();
        $comment->save();
        $this->success('评论成功');

    }


    public function processImport_old()
    {
        $fileUrl = $this->request->post('fileUrl');
        $sheetName = $this->request->post('sheetName');


        if (empty($fileUrl) || empty($sheetName)) {
            $this->error('文件URL和Sheet名称不能为空');
        }

        // FastAdmin 的文件存储通常在 public/uploads/
        // 这里假设 $fileUrl 是从 FastAdmin 的上传接口返回的相对路径，例如 /uploads/20250617/xxx.xls
        $localFilePath = ROOT_PATH . 'public' . str_replace('/', DS, $fileUrl);


        if (!file_exists($localFilePath)) {
            $this->error('服务器上找不到文件，请确认文件已正确上传路径：' . $localFilePath);
        }

        $importedCount = 0;
        $updatedCount = 0;
        $skippedCount = 0;
        $failedCount = 0;
        $errorMessages = [];
        $customerModel = new CustomerModel();

        $spreadsheet = IOFactory::load($localFilePath);
        $sheet = $spreadsheet->getSheetByName($sheetName);

        if (!$sheet) {
            $this->error('指定的Sheet名称不存在：' . $sheetName);
        }

        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn(); // 比如 'BO'
        $maxColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        $header = [];
        for ($i = 1; $i <= $maxColIndex; $i++) {
            $header[] = trim($sheet->getCellByColumnAndRow($i, 1)->getValue());
        }

        // 定义 Excel 表头到数据库字段的映射 (根据 exportExcel 的 fieldMap )
        $excelToDbMap = [
            '跟进客户' => 'customer_id',
            '跟进时间' => 'followtime', // 这是显示名称，如果数据库需要ID，需要额外处理
            '跟进方式' => 'follow_type',
            '本次沟通情况' => 'communication_status',
            '备注信息' => 'remark',
            '下次跟进时间' => 'nexttime',
            '证据图片上传' => 'images',
            '负责人' => 'staff_id',
            '创建人' => 'user_id',
        ];
        // 缓存用户名称到ID的映射，避免循环查询
        $userCache = [];

        for ($rowNum = 2; $rowNum <= $highestRow; $rowNum++) { // 从第二行开始读取数据
            $rowData = [];
            $rowError = [];

            for ($i = 1; $i <= $maxColIndex; $i++) {
                $headerIndex = $i - 1;

                if (!isset($header[$headerIndex])) {
                    continue;
                }

                $headerName = $header[$headerIndex];
                $cellValue = $sheet->getCellByColumnAndRow($i, $rowNum)->getValue();

                if (isset($excelToDbMap[$headerName])) {
                    $dbField = $excelToDbMap[$headerName];
                    $rowData[$dbField] = $cellValue;
                }
            }

            if (empty($rowData) || !array_filter($rowData)) { // 跳过空行
                continue;
            }

            $customerData = [];
            foreach ($rowData as $key => $value) {
                $value=trim($value);
                // 根据 createCustomer 方法的逻辑处理字段
                switch ($key) {
                    case 'customer_id':
                        $customer_id=$customerModel->where('customerName', $value)->value('id');
                        $customerData[$key]=$customer_id;
                        break;
                    case 'followtime':
                        $customerData[$key]=$value;
                        break;
                    case 'follow_type':
                        $customerData[$key] =$value;
                        break;
                    case 'communication_status':
                        $customerData[$key] = $value;
                        break;
                    case 'remark':
                        $customerData[$key] = $value;
                        break;
                    case 'nexttime':
                        $customerData[$key] = $value;
                        break;
                    case 'images': // 负责人姓名（如果从Excel导入）
                        $customerData[$key] = $value;
                        break;
                    case 'staff_id': // 负责人姓名（如果从Excel导入）
                        $userModel=new User();
                        $staff_id=$userModel->where('name',$value)->value('id');
                        $customerData[$key] = $staff_id;
                        break;
                    case 'user_id': // 负责人姓名（如果从Excel导入）
                        $userModel=new User();
                        $staff_id=$userModel->where('name',$value)->value('id');
                        $customerData[$key] = $staff_id;
                        break;
                    default:
                        $customerData[$key] = $value;
                        break;
                }

            }

            // 插入新客户
            $newFollow = new FollowModel();
            $customerData['user_id']=$this->auth->id;
            $res = $newFollow->save($customerData);
            if ($res !== false) {
                $importedCount++;
            } else {
                $failedCount++;
                $rowError[] = "插入失败（" . ($newFollow->getError() ?: '未知错误') . "）。";
                $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
            }

        }

        Db::name('import_log')->insert(
            [
                'success'=>$importedCount,
                'fail'=>$failedCount,
                'url'=>$fileUrl,
                'name'=>$sheetName,
                'total'=>$importedCount+$failedCount,
                'type'=>2,
                'user_id'=>$this->auth->id
            ]
        );
        $this->success('导入完成', [
            'imported' => $importedCount,
            'updated' => $updatedCount,
            'skipped' => $skippedCount,
            'failed' => $failedCount,
            'errors' => $errorMessages
        ]);

    }

    public function processImport()
    {
        $fileUrl = $this->request->post('fileUrl');
        $sheetName = $this->request->post('sheetName');
        $fieldMappings = $this->request->post('fieldMappings/a', []); // 前端传的映射关系

        if (empty($fileUrl) || empty($sheetName) || empty($fieldMappings)) {
            $this->error('文件URL、Sheet名称和字段映射不能为空');
        }

        $localFilePath = ROOT_PATH . 'public' . str_replace('/', DS, $fileUrl);
        if (!file_exists($localFilePath)) {
            $this->error('服务器上找不到文件，请确认文件已正确上传路径：' . $localFilePath);
        }

        $importedCount = 0;
        $updatedCount = 0;
        $skippedCount = 0;
        $failedCount = 0;
        $errorMessages = [];

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($localFilePath);
        $sheet = $spreadsheet->getSheetByName($sheetName);
        if (!$sheet) {
            $this->error('指定的Sheet名称不存在：' . $sheetName);
        }

        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $maxColIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);

        // 1. 生成 Excel列名 => 列号 的映射
        $excelHeaderMap = [];
        for ($i = 1; $i <= $maxColIndex; $i++) {
            $headerName = trim($sheet->getCellByColumnAndRow($i, 1)->getValue());
            if ($headerName !== '') {
                $excelHeaderMap[$headerName] = $i;
            }
        }

        // 2. 生成 系统字段 => [excel列名, 默认值, 列号] 的映射
        $fieldMap = [];
        foreach ($fieldMappings as $map) {
            $sysField = $map['systemField'];
            $excelField = $map['excelField'];
            $defaultValue = $map['defaultValue'];
            $colIndex = isset($excelHeaderMap[$excelField]) ? $excelHeaderMap[$excelField] : null;
            $fieldMap[$sysField] = [
                'excelField' => $excelField,
                'defaultValue' => $defaultValue,
                'colIndex' => $colIndex
            ];
        }

        $customerModel = new CustomerModel();


        for ($rowNum = 2; $rowNum <= $highestRow; $rowNum++) { // 从第二行开始
            $rowData = [];
            $rowError = [];

            // 3. 按系统字段组装数据
            foreach ($fieldMap as $sysField => $info) {


                $value = '';
                if ($info['colIndex']) {
                    $cellValue = $sheet->getCellByColumnAndRow($info['colIndex'], $rowNum)->getValue();
                    $value = trim($cellValue);
                }
                if ($value === '' && $info['defaultValue'] !== '') {
                    $value = $info['defaultValue'];
                }

                // 特殊处理日期/时间字段
                if ($value === '' || $value === null) {
                    $value = null; // 空值设为 null
                } else {
                    if($sysField=='customer_id'){
                        $customer=$customerModel->where('customerName',$value)->find();
                        if($customer){
                            $value = $customer['id'];
                        }else{
                            $value='';
                        }                    }
                }
                $rowData[$sysField] = $value;
            }

            if (empty($rowData) || !array_filter($rowData)) {
                continue;
            }
            //创建人
            $rowData['user_id'] = $this->auth->id;
            if (empty($rowData['customer_id'])) {
                $failedCount++;
                continue;
            }



            $followModel=new FollowModel();
            $res = $followModel->save($rowData);
            if ($res !== false) {
                $importedCount++;
            } else {
                $failedCount++;
                $rowError[] = "插入失败（" . ($followModel->getError() ?: '未知错误') . "）。";
                $errorMessages[] = "第 {$rowNum} 行：" . implode(' ', $rowError);
            }

        }

        Db::name('import_log')->insert([
            'success' => $importedCount,
            'fail' => $failedCount,
            'url' => $fileUrl,
            'name' => $sheetName,
            'type' => 2,
            'total' => $importedCount + $failedCount,
            'user_id' => $this->auth->id,
            'createtime' => date('Y-m-d H:i:s'),
        ]);

        $this->success('导入完成', [
            'imported' => $importedCount,
            'updated' => $updatedCount,
            'skipped' => $skippedCount,
            'failed' => $failedCount,
            'errors' => $errorMessages
        ]);
    }

    public function importlog()
    {
        // 获取分页参数
        $page = $this->request->post('page', 1);
        $pageSize = $this->request->post('pageSize', 20);

        // 查询条件
        $where = [];
        $userId = $this->auth->id;
        $where['type']=2;
        $where['user_id']=$userId;

        $importlog = new \app\common\model\Importlog();
        $total = $importlog->where($where)->count();
        $list = $importlog
            ->with(['user' => function($query) {
                $query->field('id,name');
            }])
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $pageSize)
            ->select();

        $request = \think\Request::instance();
        $domain = $request->domain();
        foreach ($list as $k => $v) {
            $list[$k]['url'] = $domain . $v['url'];
        }
        $this->success('请求成功', ['list' => $list, 'total' => $total]);
    }

    /**
     * 构建查询条件
     * @param array $params 查询参数
     * @param int $type 查询类型
     * @return array
     */
    private function buildWhere($params, $type)
    {
        $where = [];
        $where['a.is_delete'] = 0;

                
        // 数据权限
        $userPermissionService = new \app\common\service\UserPermissionService();
        $staffids=$userPermissionService->getUsersByPermission($this->auth->id);
        $where['a.staff_id']=['in',$staffids];
        
        // 搜索关键词
        $searchKey = isset($params['searchKey']) ? $params['searchKey'] : '';
        if ($searchKey) {
            $where['c.customerName|c.phone|c.uidipin'] = ['like', "%{$searchKey}%"];
        }
        if (isset($params['customerName']) && !empty($params['customerName'])) {
            $where['c.customerName'] = $params['customerName'];
        }
        if (isset($params['followType']) && !empty($params['followType'])) {
            $where['a.follow_type'] = $params['followType'];
        }
        if (isset($params['followTimeEnd']) && !empty($params['followTimeEnd'])) {
            $followTimeStart = $params['followTimeStart'];
            $followTimeEnd = $params['followTimeEnd'];
            $where['a.followtime'] = ['between', [$followTimeStart, $followTimeEnd]];
        }

        $userId = $this->auth->id;
        switch ($type) {
            case 1:
                break;
            case 2:
                $where['a.staff_id'] = $userId;
                break;
            case 3:
                $staffids = Db::name('user')->where('leader_id', $userId)->column('id');
                if ($staffids) {
                    $where['a.staff_id'] = ['in', $staffids];
                } else {
                    $where['a.staff_id'] = 0; // 不会有结果
                }
                break;
            case 4:
                // 今日没有跟进的客户（可选实现，通常前端用统计接口展示，列表一般不查这个）
                // 这里给出一种实现方式：查出今日未跟进的客户id，再查这些客户的最后一条跟进
                $todayStart = strtotime(date('Y-m-d 00:00:00'));
                $todayEnd = strtotime(date('Y-m-d 23:59:59'));
                $followedCustomerIds = (new \app\common\model\Follow())
                    ->where('a.followtime', 'between', [$todayStart, $todayEnd])
                    ->distinct(true)
                    ->column('customer_id');
                if ($followedCustomerIds) {
                    $where['a.customer_id'] = ['not in', $followedCustomerIds];
                }
                break;
            case 5:
                $todayStart = strtotime(date('Y-m-d 00:00:00'));
                $todayEnd = strtotime(date('Y-m-d 23:59:59'));
                $where['a.followtime'] = ['between', [$todayStart, $todayEnd]];
                break;
            default:
                break;
        }
        return $where;
    }

    /**
     * 处理导出功能
     * @param array $where 查询条件
     * @param array $params 请求参数
     * @return \think\response\Json
     */
    private function handleExport($where, $params)
    {
        // 获取导出参数
        $export_type = $this->request->post('export_type', 'all'); // 导出类型：selected, currentPage, all
        $fields = $this->request->post('fields'); // 选中的字段
        $selectedIds = $this->request->post('ids', []); // 选中的ID列表

        // 如果没有选择字段，返回错误
        if (empty($fields)) {
            $this->error('请选择要导出的字段');
        }
        $fields = explode(',', $fields);

        // 根据导出类型构建查询
        $follow = new \app\common\model\Follow();
        switch ($export_type) {
            case 'selected':
                if (empty($selectedIds)) {
                    $this->error('请选择要导出的数据');
                }
                $list = $follow
                    ->alias('a')
                    ->join('user u', 'a.user_id = u.id', 'left')
                    ->join('customer c', 'a.customer_id = c.id', 'left')
                    ->field('a.*, u.name as username,c.customerName')
                    ->where($where)
                    ->whereIn('a.id', $selectedIds)
                    ->order('a.id', 'desc')
                    ->select();
                break;
            case 'currentPage':
                $list = $follow
                    ->alias('a')
                    ->join('user u', 'a.user_id = u.id', 'left')
                    ->join('customer c', 'a.customer_id = c.id', 'left')
                    ->field('a.*, u.name as username,c.customerName')
                    ->where($where)
                    ->whereIn('a.id', $selectedIds)
                    ->order('a.id', 'desc')
                    ->select();
                break;
            case 'all':
            default:
                $list = $follow
                    ->alias('a')
                    ->join('user u', 'a.user_id = u.id', 'left')
                    ->join('customer c', 'a.customer_id = c.id', 'left')
                    ->field('a.*, u.name as username,c.customerName')
                    ->where($where)
                    ->order('a.id', 'desc')
                    ->select();
                break;
        }

        // 创建新的 Spreadsheet 对象
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 字段映射表
        $fieldMap = [
            'customerName' => '跟进客户',
            'followtime' => '跟进时间',
            'follow_type' => '跟进方式',
            'communication_status' => '本次沟通情况',
            'phone' => '手机号',
            'remark' => '备注信息',
            'user_id' => '创建人',
            'staff_id' => '负责人',
            'images' => '证据图片',
            'department_id' => '部门',
            'createtime' => '创建时间',
            'updatetime' => '更新时间',
           
        ];

        // 写入表头
        $col = 1;
        foreach ($fields as $field) {
            if (isset($fieldMap[$field])) {
                $sheet->setCellValueByColumnAndRow($col, 1, $fieldMap[$field]);
                $col++;
            }
        }

        // 写入数据
        $row = 2;
        foreach ($list as $item) {
            $col = 1;
            $itemArr = $item->toArray();
            foreach ($fields as $field) {
                $value = $itemArr[$field] ?? '';

                // 处理特殊字段
                switch ($field) {
                    case 'createtime':
                        $value = $value ? date('Y-m-d H:i:s', is_numeric($value) ? $value : strtotime($value)) : '';
                        break;
                    case 'updatetime':
                        $value = $value ? date('Y-m-d H:i:s', is_numeric($value) ? $value : strtotime($value)) : '';
                        break;
                    case 'followtime':
                        $value = $value ? date('Y-m-d H:i:s', is_numeric($value) ? $value : strtotime($value)) : '';
                        break;
                    case 'communication_status':
                        $value = is_string($value) ? $value : json_encode($value, JSON_UNESCAPED_UNICODE);
                        break;
                    case 'user_id':
                        $value = $itemArr['username'] ?? '';
                        break;
                    case 'staff_id':
                        // 关联用户表获取员工姓名
                        if ($value) {
                            $user = Db::name('user')->where('id', $value)->field('name')->find();
                            $value = $user ? $user['name'] : '';
                        }
                        break;
                    case 'department_id':
                        // 关联部门表获取部门名称
                        if ($value) {
                            $dept = Db::name('department')->where('id', $value)->field('title')->find();
                            $value = $dept ? $dept['title'] : '';
                        }
                        break;
                    case 'customerName':
                        $value = $itemArr['customerName'] ?? '';
                        break;
                    case 'images':
                        // 处理回款信息截图字段，插入图片到单元格，横向排列
                        $request = Request::instance();
                        $domain = $request->domain();
                        $cellCoordinate = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($col) . $row;
                        if (!empty($value) && is_string($value)) {
                            $images = json_decode($value, true);
                            if (is_array($images)) {
                                $imgOffsetX = 0;
                                foreach ($images as $imgPath) {
                                    // 确保 $imgPath 是字符串
                                    if (!is_string($imgPath)) {
                                        continue;
                                    }
                                    if (strpos($imgPath, 'http') === 0) {
                                        $imgUrl = $imgPath;
                                    } else {
                                        $imgUrl = $domain . $imgPath;
                                    }
                                    $localPath = str_replace($domain, '', $imgUrl);
                                    $localPath = ROOT_PATH . 'public' . str_replace('/', DS, $localPath);
                                    if (is_file($localPath)) {
                                        $drawing = new Drawing();
                                        $drawing->setPath($localPath);
                                        $drawing->setHeight(20);
                                        $drawing->setWidth(20);
                                        $drawing->setCoordinates($cellCoordinate);
                                        $drawing->setOffsetX($imgOffsetX);
                                        $drawing->setOffsetY(0);
                                        $drawing->setWorksheet($sheet);
                                        $imgOffsetX += 10; // 横向排列，图片之间有间隔
                                    }
                                }
                                $value = '';
                            }
                        }
                        break;
                }

                $sheet->setCellValueByColumnAndRow($col, $row, $value);
                $col++;
            }
            $row++;
        }

        // 设置列宽
        for ($i = 1; $i <= count($fields); $i++) {
            $sheet->getColumnDimensionByColumn($i)->setWidth(30);
        }

        // 设置表头样式
        $headerStyle = [
            'font' => ['bold' => true],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
            ],
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'startColor' => ['rgb' => 'E0E0E0']
            ]
        ];
        $sheet->getStyle('A1:' . $sheet->getHighestColumn() . '1')->applyFromArray($headerStyle);

        // 设置数据区域样式
        $dataStyle = [
            'borders' => [
                'allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
            ]
        ];
        $sheet->getStyle('A2:' . $sheet->getHighestColumn() . ($row - 1))->applyFromArray($dataStyle);

        // 生成文件名
        $filename = '跟进数据_' . date('YmdHis') . '.xlsx';

        // 确保目录存在
        $savePath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'excel';
        if (!is_dir($savePath)) {
            mkdir($savePath, 0755, true);
        }

        // 完整的文件保存路径
        $filePath = $savePath . DS . $filename;

        // 保存文件
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
        $writer->save($filePath);

        // 返回文件URL给前端
        $request = Request::instance();
        $domain = $request->domain();
        $fileUrl = $domain . '/uploads/excel/' . $filename;
        $this->success('导出成功', ['url' => $fileUrl]);
    }


}
